package com.example.nutritionmate.service;

import com.example.nutritionmate.dto.CreateMealRecordDTO;
import com.example.nutritionmate.dto.NutrientAmountDTO;
import com.example.nutritionmate.entity.*;
import com.example.nutritionmate.repository.MealNutritionRepository;
import com.example.nutritionmate.repository.MealRecordRepository;
import com.example.nutritionmate.repository.MealRepository;
import com.example.nutritionmate.repository.NutritionFactRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
public class RecordService {
    @Autowired
    private MealRepository mealRepository;
    @Autowired
    private MealRecordRepository mealRecordRepository;
    @Autowired
    private NutritionFactRepository nutritionFactRepository;
    @Autowired
    private MealNutritionRepository mealNutritionRepository;
    /**
     * 添加一条饮食记录
     *
     * @param user                   当前用户
     * @param createMealRecordDTO    请求传来的饮食记录DTO
     * @return                       保存后的 MealRecord 实体
     */
    @Transactional
    public MealRecord addMealRecord(User user, CreateMealRecordDTO createMealRecordDTO) {
        // 1. 查找或创建 Meal
        Meal meal = mealRepository.findByDateAndMealType(createMealRecordDTO.getDate(), createMealRecordDTO.getMealType())
                .orElseGet(() -> {
                    Meal newMeal = new Meal();
                    newMeal.setDate(createMealRecordDTO.getDate());
                    newMeal.setMealType(createMealRecordDTO.getMealType());
                    return mealRepository.save(newMeal);
                });

        // 2. 创建 MealRecord
        MealRecord mealRecord = new MealRecord();
        mealRecord.setUser(user);
        mealRecord.setMeal(meal);
        mealRecord.setQuantity(null); // 根据需求设置数量，如果有对应字段
        mealRecord = mealRecordRepository.save(mealRecord);

        // 3. 创建 MealNutrition 记录
        for (NutrientAmountDTO nutrientAmount : createMealRecordDTO.getNutrients()) {
            // 根据 nutritionId 查找 NutritionFact
            Optional<NutritionFact> nutritionFact = nutritionFactRepository.findById(nutrientAmount.getNutritionId());
            MealNutrition mealNutrition = new MealNutrition();
            mealNutrition.setMealRecord(mealRecord);
            mealNutrition.setNutritionFact(nutritionFact.get());
            mealNutrition.setAmount(nutrientAmount.getAmount());
            mealNutrition.setId(new MealNutritionId(mealRecord.getRecordId(), nutritionFact.get().getNutritionId()));
            mealNutritionRepository.save(mealNutrition);
        }

        return mealRecord;
    }
}
